import datetime

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from com.user.sign_in_controller import is_sign_in
from smart_monitor.models import Terminal as t_db_m
from smart_monitor.models import DateData as d_db_m
from my_models.date_data_model import DateData as d_m
from my_models.common_model import SelectModel


def query(request):
    if 'inputStartTime' and 'inputEndTime' in request.POST:
        start_time = request.POST["inputStartTime"]
        end_time = request.POST["inputEndTime"]
        try:
            y, m, d = start_time.split("T")[0].split("-")
            h, mi = start_time.split("T")[1].split(":")
            date_time_from = datetime.datetime(int(y), int(m), int(d), int(h), int(mi))
            y, m, d = end_time.split("T")[0].split("-")
            h, mi = end_time.split("T")[1].split(":")
            date_time_to = datetime.datetime(int(y), int(m), int(d), int(h), int(mi))
        except Exception as e:
            return render(request, "404.html", {"error_info": "输入不合法"})

        data_set = d_db_m.objects.filter(record_time__range=(date_time_from, date_time_to),
                                         terminal_db=request.session.get("terminal_id", 1))
        datas = []
        for data_obj in data_set:
            datas.append(d_m(data_obj.communicator_id, data_obj.terminal_id,
                             data_obj.terminal_db_id, data_obj.record_time,
                             data_obj.sys_state, data_obj.en_state,
                             data_obj.mode, data_obj.power_produce, data_obj.net_voltage_a,
                             data_obj.net_voltage_b, data_obj.net_frequence, data_obj.mechine_voltage_a,
                             data_obj.mechine_voltage_b, data_obj.mechine_frequence,
                             data_obj.mechine_current_a, data_obj.mechine_voltage_b,
                             data_obj.mechine_current_c, data_obj.useful_power, data_obj.useless_power,
                             data_obj.power_factor, data_obj.excite_voltage, data_obj.excite_current,
                             data_obj.water_level, data_obj.increase_state, data_obj.decrease_state,
                             data_obj.battery, data_obj.temperature))
        html_data_set = {
            "function": "query",
            "datas": datas,
            "user_name": request.session["user_name"],
            "communicator_id": request.session["communicator_id"],
            "terminal_id": request.session["terminal_id"]}
        return render(request, "manage_console.html", html_data_set)


def cmd(request):
    print(request.POST)
    return render(request, "404.html", {})


def his_state(request):
    pass


def analysis(request):
    pass


def diagnose(request):
    pass


MANAGE_FUNCTIONS = {"query": query, "history_state": his_state,
                    "cmd": cmd, "analysis": analysis, "diagnose": diagnose}


def query_get(request, data_set):
    data_set["communicator_id"] = request.session["communicator_id"]
    data_set["terminal_id"] = request.session["terminal_id"]
    return render(request, "manage_console.html", data_set)


def cmd_get(request, data_set):

    if request.is_ajax():
        print(request.GET)
        return HttpResponse("可以可以")
    data_set["communicator_id"] = request.session["communicator_id"]
    data_set["terminal_id"] = request.session["terminal_id"]
    data_set["opt_state"] = "请执行操作"
    cmd_options_list = ["开机", "关机", "开增", "开减", "紧急关机"]
    query_option_list = ["全部参数", "工作时间", "并网时间", "总发电量", "目标水位", "关机水位", "总开增次数", "本次并网有功","最大功率因素","最大励磁电压","开度首次动作时间", "水位高度功率因数","最大功率步长时间",
                         "额定电流", "终端时间", "额定功率", "总无功量", "溢洪水位", "开机水位", "总开减次数", "本次并网无功","电流传输比值","最大励磁电流","开度动作最小时间", "水位变化功率系数", "最小功率步长时间", "开度关闭最长时间"]
    query_options = []
    for value, n in enumerate(query_option_list):
        query_options.append(SelectModel(n, value))
    data_set["query_options"] = query_options
    cmd_options = []
    for value, n in enumerate(cmd_options_list):
        cmd_options.append(SelectModel(n, value))
    data_set["query_options"] = query_options
    data_set["cmd_options"] = cmd_options
    return render(request, "manage_console.html", data_set)


def his_state_get(request, data_set):
    data_set["communicator_id"] = request.session["communicator_id"]
    data_set["terminal_id"] = request.session["terminal_id"]
    return render(request, "manage_console.html", data_set)


def analysis_get(request, data_set):
    data_set["communicator_id"] = request.session["communicator_id"]
    data_set["terminal_id"] = request.session["terminal_id"]
    return render(request, "manage_console.html", data_set)


def diagnose_get(request, data_set):
    data_set["communicator_id"] = request.session["communicator_id"]
    data_set["terminal_id"] = request.session["terminal_id"]
    return render(request, "manage_console.html", data_set)


MANAGE_GET_FUNCTIONS = {"query": query_get, "history_state": his_state_get,
                         "cmd": cmd_get, "analysis": analysis_get, "diagnose": diagnose_get}


class Manage(object):
    def __init__(self, request, *args):
        self.request = request
        self.terminal_id = None
        self.function = None
        arg = args[0][0]
        for flag in MANAGE_FUNCTIONS.keys():
            if flag == arg:
                self.function = flag
        if not self.function:
            self.terminal_id = arg

    def run(self):
        sign_in, user_name = is_sign_in(self.request)
        if not sign_in:
            return HttpResponseRedirect("/user/sign_in")
        data_set = {"function": "query", "user_name": user_name, "communicator_id": 0, "terminal_id": 0}
        if self.terminal_id:
            try:
                terminal = t_db_m.objects.get(id=self.terminal_id)
            except Exception as e:
                return render(self.request, "404.html", {})
            self.request.session["terminal_id"] = self.terminal_id
            self.request.session["communicator_id"] = terminal.communicator_id
            return render(self.request, "manage_console.html", data_set)
        else:
            data_set["function"] = self.function
            if self.request.method == "POST":
                return MANAGE_FUNCTIONS[self.function](self.request)
            else:
                return MANAGE_GET_FUNCTIONS[self.function](self.request, data_set)
